import { getCityByParentId } from '@/apis/city'
import { register } from '@/apis/register'
import { reactive, ref } from 'vue'
import { RegisterBaseInformationData } from '../base/index'
import { isPC, uploadImage } from '@/utils'
import { CxlMessage } from '@/components/message'
import ImageDirection from '@/utils/changeImageDirection'

export class RegisterData extends RegisterBaseInformationData {
    data: any = reactive({
        companyName: '',
        socialCreditCode: '',
        companyBusinessImageKey: '',
        address: '',
        province: '',
        introducerCode: ''
    })
    //公司名称
    companyName = ref('')
    //统一社会信用代码
    socialCreditCode = ref('')
    //营业执照
    companyBusinessImageKey = ref('')
    //本地图片展示
    localImageUrl = ref('')
    //公司地址
    address = ref('')
    //选择的省
    province = ref('')
    provinceId = ref('')
    //省级列表
    provinceOptions: any[] = reactive([])
    //选择的市
    city = ref('')
    cityId = ref('')
    //市级列表
    cityOptions: any[] = reactive([])
    //是否勾选协议
    isCheck = ref(false)
    //提交审核弹窗
    submitVisible = ref(false)
    //审核中弹窗
    auditVisible = ref(false)
    //图片上传状态
    uploading = ref(false)
    //
    isPending = false
    timer: any
    isPc = ref(false)
    //检查是否选择了省
    isSelectProvince = ref(true)
    //检查是否选择了市
    isSelectCity = ref(true)
    //是否上传了图片
    isUploadImg = ref(true)
    //是否勾选了协议
    isSelectCheck = ref(true)
    //退出申请
    quitVisible = ref(false)
    //图片旋转 图像方向。 - - 1：未定义， - 0：正向， - 1：逆时针90度， - 2：逆时针180度， - 3：逆时针270度
    imageDirection = ref(0)
    //是否提交注册了
    isSubmitRegister = ref(false)
    //推荐人编码
    introducerCode = ref('')
    constructor() {
        super()
        this.isPc.value = isPC()
    }
    //重置数据
    reset = () => {
        this.companyName.value = ''
        this.socialCreditCode.value = ''
        this.companyBusinessImageKey.value = ''
        this.localImageUrl.value = ''
        this.province.value = ''
        this.provinceId.value = ''
        this.city.value = ''
        this.cityId.value = ''
        this.cityOptions.length = 0
        this.isCheck.value = false
        this.submitVisible.value = false
        this.auditVisible.value = false
        this.uploading.value = false
        this.isPending = false
        this.timer = 0
        this.isSelectProvince.value = true
        this.isSelectCity.value = true
        this.isUploadImg.value = true
        this.isSelectCheck.value = true
        this.data.companyName = ''
        this.data.socialCreditCode = ''
        this.data.companyBusinessImageKey = ''
        this.data.address = ''
        this.data.province = ''
        this.introducerCode.value = ''
    }
    /**
     * 根据id获取省|市
     * @param id
     * @param province
     */
    cityByParentId = (id: string, province = true) => {
        getCityByParentId(id).then((res: any) => {
            if (res.data.value === 200) {
                if (province) {
                    //省
                    this.provinceOptions.length = 0
                    res.data.data.forEach((element: any) => {
                        this.provinceOptions.push(element)
                    })
                } else {
                    //市
                    this.cityOptions.length = 0
                    res.data.data.forEach((element: any) => {
                        this.cityOptions.push(element)
                    })
                    if (this.cityOptions.length === 0) {
                        this.isSelectCity.value = true
                    }
                }
            }
        })
    }
    /**
     * 监听选择的省
     * @param res
     */
    onSelectProvince = (res: any) => {
        console.log('on select province', res)
        this.cityOptions.length = 0
        this.city.value = ''
        this.province.value = res.name
        this.provinceId.value = res.id
        this.cityByParentId(res.id, false)
        this.isSelectProvince.value = true
        this.isSelectCity.value = true
    }
    /**
     * 监听选择的市
     * @param res
     */
    onSelectCity = (res: any) => {
        this.city.value = res.name
        this.cityId.value = res.id
        console.log('on select city', res)
        this.isSelectProvince.value = true
        this.isSelectCity.value = true
    }

    /**
     * 上传图片
     */
    uploadFile = () => {
        uploadImage({
            start: () => {
                this.isUploadImg.value = true
                this.uploading.value = true
            },
            succeed: (localData, result) => {
                console.log('url', result)
                // this.localImageUrl.value = localData
                this.companyBusinessImageKey.value = result.data.data.businessLicenseKey
                this.uploading.value = false
                this.companyName.value = result.data.data.unitName
                this.socialCreditCode.value = result.data.data.socialCreditCode
                this.imageDirection.value = result.data.data.direction

                new ImageDirection().init(localData, result.data.data.direction, (url: string) => {
                    this.localImageUrl.value = url
                })
            },
            failed: () => {
                this.uploading.value = false
            }
        })
    }
    //PC端上传图片
    onUploadFileBase64 = (base64: string) => {
        console.log('base64', base64)
        uploadImage({
            start: () => {
                this.isUploadImg.value = true
                this.uploading.value = true
            },
            succeed: (localData, result) => {
                console.log('url', result)
                // this.localImageUrl.value = base64
                this.companyBusinessImageKey.value = result.data.data.businessLicenseKey
                this.uploading.value = false
                this.companyName.value = result.data.data.unitName
                this.socialCreditCode.value = result.data.data.socialCreditCode
                this.imageDirection.value = result.data.data.direction
                new ImageDirection().init(localData, result.data.data.direction, (url: string) => {
                    this.localImageUrl.value = url
                })
            },
            failed: () => {
                this.uploading.value = false
            },
            base64
        })
    }

    //监听勾选协议
    onCheckChange = () => {
        this.isSelectCheck.value = true
    }

    /**
     * 监听基本信息
     */
    onBaseInformationUpdate = (res: any) => {
        this.phone.value = res.phone
        this.code.value = res.code
        this.password.value = res.password
        this.passwordAgain.value = res.passwordAgain
    }
    isCheckSocialCreditCode = false
    checkSocialCreditCode = () => {
        // if (
        //     this.socialCreditCode.value.length &&
        //     !CheckSocialCreditCode(this.socialCreditCode.value) &&
        //     !this.isCheckSocialCreditCode
        // ) {
        //     this.isCheckSocialCreditCode = true
        //     CxlMessage.error('您输入的统一社会信用代码有误，请重新输入！', () => {
        //         this.isCheckSocialCreditCode = false
        //     })
        // }
    }
    /**
     * 提交资料进行注册
     */
    onSubmitRegister = (baseRef: any, companyRef: any, socialCreditCodeRef: any, boxRef: any) => {
        console.log(baseRef)
        const a = baseRef.validate()
        const b = companyRef.validateInput()
        const c = socialCreditCodeRef.validateInput()
        if (this.province.value === '') {
            this.isSelectProvince.value = false
        } else if (this.city.value === '' && this.cityOptions.length !== 0) {
            this.isSelectCity.value = false
        }

        if (this.companyBusinessImageKey.value === '') {
            this.isUploadImg.value = false
        }
        if (this.isCheck.value === false) {
            this.isSelectCheck.value = false
        }
        if (!a) {
            boxRef.scrollTo({
                top: 60,
                behavior: 'smooth'
            })
            console.log(boxRef)
        }

        if (
            a &&
            b &&
            c &&
            this.isSelectProvince.value &&
            this.isSelectCity.value &&
            this.isUploadImg.value &&
            this.isSelectCheck.value
        ) {
            if (this.isPending) {
                return
            }
            this.isPending = true
            register({
                code: this.code.value,
                companyAddress: this.cityOptions.length === 0 ? this.provinceId.value : this.cityId.value,
                companyBusinessImageKey: this.companyBusinessImageKey.value,
                companyCode: this.socialCreditCode.value,
                companyName: this.companyName.value,
                password: this.password.value,
                phone: this.phone.value,
                introducerCode: this.introducerCode.value
            }).then((res: any) => {
                this.isPending = false
                if (res.data.value === 200) {
                    // CxlMessage.success('注册信息已提交审核，请耐心等待！')
                    this.submitVisible.value = true
                    // this.timer = setTimeout(() => {
                    //     router.replace('/login')
                    //     clearTimeout(this.timer)
                    // }, 5000)
                    this.isSubmitRegister.value = true
                } else if (res.data.value === 10002) {
                    this.auditVisible.value = true
                } else {
                    CxlMessage.error(res.data.desc)
                }
            })
        }
    }
    /**
     * 打开协议
     */
    onOpenProtocol = (type: string) => {
        this.router.push({ name: 'protocol', params: { type } })
    }
    //监听提交成功弹窗关闭
    onSubmitDialogClose = () => {
        this.router.replace('/login')
    }

    //点击取消隐藏弹窗，继续注册
    onCancelQuit = () => {
        this.quitVisible.value = false
    }
}
